﻿using System;
using System.Collections.Generic;
using System.Text;
using Clipping.Infrastructure.Interfaces;
using Clipping.Infrastructure.Models;
using System.Text.RegularExpressions;

namespace Clipping.SearchEnginePageParsers
{
	public class ChinaDailyPageParser : ISearchEnginePageParse
	{
		public void Parse(string html, out List<News> news, out string nextPageUrl)
		{
			 news = new List<News>();
            nextPageUrl = null;
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var liNav = doc.CreateNavigator();
            string h = ((HtmlAgilityPack.HtmlNodeNavigator)(liNav)).CurrentNode.OuterHtml;

            var divSearchResult = liNav.Select("//div[@class='topNews_a']");
            while (divSearchResult.MoveNext())
            {
                News n = new News();
                n.Media = "中国日报网";

                var li = divSearchResult.Current;
                
                //取标题和链接
                var linkNode = li.SelectSingleNode("descendant::a");
                if (linkNode != null)
                {
                    n.Title = n.Title = n.Title = System.Web.HttpUtility.HtmlDecode(linkNode.Value);

                    n.Url = System.Web.HttpUtility.UrlDecode(linkNode.GetAttribute("href", ""));
                }

                //取日期
                var str = li.Value;
                var titleStr = linkNode.Value;
                var dateStr = str.Replace(titleStr, "");
                var dateMatch=Regex.Match(dateStr, @"\d{4}-\d{2}-\d{2}");
                if (dateMatch.Success)
                    n.PubDate = dateMatch.Value;

                //取摘要
                var liHtml = ((HtmlAgilityPack.HtmlNodeNavigator)(li)).CurrentNode.OuterHtml;
                
               var startIndex= h.IndexOf(liHtml, StringComparison.OrdinalIgnoreCase) + liHtml.Length;
               var subStr = h.Substring(startIndex);
               var endIndex = subStr.IndexOf("<div",StringComparison.OrdinalIgnoreCase);
               n.Summary = subStr.Substring(0, endIndex);

                news.Add(n);
            }

            //取下一页地址
            var aList = liNav.Select("descendant::a");
            if (aList != null)
            {
                while (aList.MoveNext())
                {
                    
                    var a = aList.Current;
                    string npu = a.GetAttribute("href", "");
                    if (a.Value != null && a.Value.Contains("下一页") && npu.Contains("javascript:gopage"))
                    {
                        nextPageUrl = Regex.Match(npu, @"javascript:gopage\((\d+)\)").Groups[1].Value;
                        break;
                    }
                }
            }
		}
	}
}
